package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/zhongshaofa/swan-jobs/internal/repositorys"
	"github.com/zhongshaofa/swan-jobs/internal/request"
	"github.com/zhongshaofa/swan-jobs/internal/services/token"
	"github.com/zhongshaofa/swan-jobs/internal/utils/datetime"
	password2 "github.com/zhongshaofa/swan-jobs/internal/utils/password"
	"github.com/zhongshaofa/swan-jobs/internal/utils/response"
	"github.com/zhongshaofa/swan-jobs/internal/utils/validator"
)

type login struct {
	UserRepository repositorys.UserRepository
}

var Login = login{}

func (c *login) Login(gc *gin.Context) {

	var loginRequest request.LoginRequest
	err := gc.ShouldBind(&loginRequest)
	if err != nil {
		response.RespValidateError(validator.FormatValidatorError(err), gc)
		return
	}

	loginRequest.Password = password2.EncryptPassword(loginRequest.Password)

	u, err := c.UserRepository.UserLogin(loginRequest.Username, loginRequest.Password)
	if err != nil {
		response.RespValidateError("登录失败，请检查账号密码", gc)
		return
	}

	userToken := token.GetUserTokenMangerInstance().Create(u)

	var result = make(map[string]interface{})
	result["token"] = userToken.Token
	result["expire_at"] = datetime.FormatDatetime(userToken.ExpireAt)
	result["user"] = u

	response.RespSuccess(result, gc)

}

func (c *login) Out(gc *gin.Context) {
	authRequest, _ := request.GetAuthRequest(gc)

	token.GetUserTokenMangerInstance().Clear(authRequest.UserId)

	response.RespSuccess(nil, gc)
}
